package com.ruoyi;

import com.ruoyi.charge.common.GlobalConstant;
import com.ruoyi.charge.domain.ChargingStation;
import com.ruoyi.charge.service.IChargingStationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.BoundGeoOperations;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;

@Component
public class InitApplication {

    @Autowired
    IChargingStationService iChargingStationService;

    @Autowired
    RedisTemplate redisTemplate;

    @PostConstruct//方法在tomcat启动时执行,由框架调用，没有参数，没有返回值
    public void readStationWriteToRedsi(){
        System.out.println("readStationWriteToRedsi()");
        //读取charging数据库中charging_station表中的数据
        //参数是用来生成查询条件的，null表示没有条件，就是查询所有数据
        List<ChargingStation> stationList = iChargingStationService.selectChargingStationList(null);
        //org.springframework.data.geo.Point
        HashMap<String, Point> hashMap = new HashMap();

        BoundHashOperations boundHashOperations = redisTemplate.boundHashOps(GlobalConstant.STATION_DETAIL_HASH);

        //遍历所有充电站，把数据放到zset中
        for(ChargingStation chargingStation:stationList){

            //得到到充电站编号
            String id=chargingStation.getId().toString();

            //把充电站信息放到hash中
            boundHashOperations.put(id,chargingStation);

            //得到充电站的经度，纬度，封装成point
            double longitude = Double.parseDouble(chargingStation.getStationLng().toString());
            double latitude = Double.parseDouble(chargingStation.getStationLat().toString());
            Point stationPosition = new Point(longitude, latitude);

            //往hashMap中添加一个充电站信息
            hashMap.put(id,stationPosition);
        }

        BoundGeoOperations boundGeoOperations = redisTemplate.boundGeoOps(GlobalConstant.STATION_GEO_ZSET);
        //	Long add(Map<M, Point> memberCoordinateMap);
        boundGeoOperations.add(hashMap);//一次性把所有充电站写入redis
    }
}
